import {Modal, Button} from 'antd';
import {inject, observer} from "mobx-react";
import {toJS} from 'mobx';
import {
    WeaDialog,
    WeaTab,
    WeaLocaleProvider,
    WeaButtonIcon,
    WeaRichText,
    WeaRightMenu
} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import {WeaSwitch} from 'comsMobx'
import {WeaTableNew} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;

import * as blogUtil from '../../../util/index';
import ShareAddModule from "./ShareAddModule";
import './../../../style/moduleSetting.less'

@inject('blogSetting')
@observer
export default class EditMould extends React.Component {
    constructor(props){
        super(props);
        this.state={
            hasLoad:false,
            isShowCube:true,
        }
    }

    getBtns = () => {
        const {blogSetting} = this.props;
        const {selectedKey} = blogSetting.moduleStatus;
        const {templateType} = blogSetting;
        let btns = [];

        if(templateType=="1"&&selectedKey ==1){
         return btns;
        }

        if(selectedKey == 0){//基本信息
            btns.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@u2mp0u@savebaseinfo`} key="submit" type="primary"  onClick={() => this.onRightMenuClick('EDIT_BASE')}>{getLabel(30986, "保存")}</Button>
            )
        }if(selectedKey == 1){//内容设置
            btns.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6znwoo@savesetting`} key="submit" type="primary" onClick={() => this.onRightMenuClick('EDIT_CONTENT')}>{getLabel(30986, "保存")}</Button>
            )
        }
        return btns;
    }


    getRightMenu = () => {
        const {blogSetting} = this.props;
        const {selectedKey} = toJS(blogSetting.moduleStatus);
        let btns = [];
        if(selectedKey == 0){
            btns.push(
                {
                    key: 'EDIT_BASE',
                    icon: <i className='icon-coms-Preservation'/>,
                    content: getLabel(30986,"保存"),
                    onClick: () => this.onRightMenuClick('EDIT_BASE')
                }
            )
        }
        if(selectedKey == 1){
            btns.push(
                {
                    key: 'EDIT_BASE',
                    icon: <i className='icon-coms-Preservation'/>,
                    content: getLabel(30986,"保存"),
                    onClick: () => this.onRightMenuClick('EDIT_CONTENT')
                }
            )
        }
        return btns;
    }


    componentDidMount() {

        this.initCube()

    }


    //初始化建模
    initCube = () => {
        const cubeFiles = [
            `/spa/cube/static4engine/engine.js`,
            `/spa/cube/static4engine/engine.css`,
        ];
        const init = () => {
            this.setState((state, props) => ({ hasLoad: true }), () => {
                const { hasLoad } = this.state;
                if (hasLoad) {
                    const { EcmeBaseStore, CubeModeStore, CubeCommonStore } = (window.weaCubeEngine && window.weaCubeEngine.store) || {};
                    this.setState({
                        EcmeBaseStore,
                        CubeModeStore,
                        CubeCommonStore
                    })
                }
            });
        }
        loadjs.isDefined("bs_cube")
            ? loadjs.ready("bs_cube", init)
            : loadjs(cubeFiles, "bs_cube", init);
    }


    getTabBtns = () => {
        const {blogSetting} = this.props;
        const {selectedKey} = blogSetting.moduleStatus;
        const shareRowKeys = toJS(blogSetting.moduleShareTable.selectedRowKeys);
        let btns = [];

        if(selectedKey == 2){
            btns.push(
                <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@mn7cvf@addtemp`}
                    buttonType="add"
                    type="primary"
                    onClick={() => blogSetting.setModuleState({showShare: true})}
                >
                </WeaButtonIcon>,
                <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@fym94w@comfirmdel`}
                    buttonType="del"
                    type="primary"
                    disabled={shareRowKeys.length == 0}
                    onClick={() => {
                        blogUtil.doConfirm(
                            getLabel(82017,'确认删除？'),
                            () => blogSetting.operateBlogTemplateShare({operation: 'delTempShare', id: shareRowKeys.join(',')})
                        );
                    }}
                >
                </WeaButtonIcon>
            )
        }
        return btns;
    }

    onRightMenuClick = (type) => {
        const {blogSetting} = this.props;
        const {editId, richTextValue} = blogSetting.moduleStatus;
        const params  = blogSetting.moduleDialogForm && blogSetting.moduleDialogForm.getFormParams();
        if(type == 'EDIT_BASE'){
            blogSetting.operateBlogTemplateSet({operation: 'saveTemp', isSystem: 0, id: editId, ...params}, 'editBase');
        }
        if(type == 'EDIT_CONTENT'){
            blogSetting.operateBlogTemplateSet({operation: 'saveContent', tempContent: richTextValue, id: editId}, 'editContent');
        }
    }

    cubeCallback = (param) =>{
        const {blogSetting} = this.props;
        const {editId} = blogSetting.moduleStatus;

    if(param.type==1){//新建

    }else if (param.type==2){//删除
        blogSetting.operateBlogTemplateSet({operation: 'saveContent', tempContent: "", id: editId}, 'editContent');
    }else if(param.type==3){//保存
        blogSetting.operateBlogTemplateSet({operation: 'saveContent', tempContent: "", id: editId}, 'editContent');
    }

    }

    onOperatesClick = (record, index, operate) => {
        const {blogSetting} = this.props;
        if (operate.index == '0') {//删除
            blogUtil.doConfirm(getLabel(82017,'确认删除？'), () => blogSetting.operateBlogTemplateShare({operation: 'delTempShare', id: record.realId}));
        }
    }

    render() {
        const {blogSetting} = this.props;
        const {showEdit, selectedKey, richTextValue, moduleDialogFields,editId} = toJS(blogSetting.moduleStatus);
        const {templateType} = blogSetting;
        const title = getLabel(28052, "编辑模板");
        const collectParams={
            favname: title,
            favouritetype: 1,
            objid:0,
            link:'wui/engine.html#/blogengine/setting',
            importantlevel: 1,
        };
        const tabs = [
            {
                groupid: 'base',
                title: getLabel(1361,'基本信息'),
                viewcondition: '0'
            },
            {
                groupid: 'content',
                title: getLabel(385488,'模版内容设置'),
                viewcondition: '1'
            },
            {
                groupid: 'range',
                title: getLabel(19910,'共享范围'),
                viewcondition: '2'
            },
        ]
        const ckConfig = {
            toolbar: [
                { name: "document", items: ["Source"] },
                {
                    name: "paragraph",
                    items: [
                        "JustifyLeft",
                        "JustifyCenter",
                        "JustifyRight",
                        "-",
                        "NumberedList",
                        "BulletedList"
                    ]
                },
                { name: "styles", items: ["Format", "Font", "FontSize"] },
                { name: "colors", items: ["TextColor"] },
                {
                    name: "basicstyles",
                    items: ["Bold", "Italic", "Underline", "Strike"]
                },
                { name: "insert", items: ["Image", "Table", "Smiley"] },
                { name: 'tools', items: [ 'Maximize' ] }
            ],
            extraPlugins: "autogrow",
            height:300,
            autoGrow_minHeight: 300,
            autoGrow_maxHeight: 300,
            removePlugins: "resize",
            uploadUrl: "/api/blog/fileupload/uploadimage"
        }
        let EcmeSet ={};
        if(this.state.hasLoad){
            EcmeSet= (window.weaCubeEngine && window.weaCubeEngine.com && window.weaCubeEngine.com.EcmeSet) || {};
        }


        let windowHeight= jQuery(window).height();
        let dialogheight=510;
        let hhe = 400;
        if(templateType=="1"&&selectedKey == 1){
            hhe = 633;
            dialogheight=743;
        }

        let topp = (windowHeight - dialogheight)/2;
        jQuery(jQuery(".blogEcmeDmo .ant-modal")[0]).css({'top':topp});
        
        return (
            <div >
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@5ki2y2`}
                    title={title}
                    icon="icon-coms-blog"
                    iconBgcolor="#6d3cf7"
                    parentClassName="blogEcmeDmo"
                    visible={showEdit}
                    className='blog-mask'
                    buttons={this.getBtns()}
                    onCancel={() => {
                        blogSetting.setModuleState({showEdit: false, richTextValue: ''});
                        blogSetting.doModuleFormInit();
                    }}
                    style={{width: 760, height: hhe}}
                    moreBtn={{collectParams: collectParams}}
                >
                    <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@l67mir`}
                        datas={tabs}
                        keyParam="viewcondition"
                        countParam="groupid"
                        selectedKey={selectedKey}
                        onChange={v => blogSetting.setModuleState({selectedKey: v})}
                        buttons={this.getTabBtns()}
                    />
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@g3p6k6`}
                        datas={this.getRightMenu()}
                        collectParams={{collectParams}}
                    >
                        {selectedKey == 0 && blogUtil.getFormSearchs(blogSetting.moduleDialogForm, moduleDialogFields,false,false,false,this.props.ecId || '')}
                        {selectedKey == 1  &&
                        <div style={{padding: '15px 10px'}}>
                            <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@5dwocy`}
                                ckConfig={ckConfig}
                                value={richTextValue}
                                onChange={v => blogSetting.setModuleState({richTextValue: v})}
                            />
                        </div>}
                        {selectedKey == 2 &&
                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@d1766b`}
                            hasOrder={true}
                            needScroll={true}
                            comsWeaTableStore={blogSetting.moduleShareTable}
                            onOperatesClick={this.onOperatesClick}
                        />}
                    </WeaRightMenu>
                </WeaDialog>
                <ShareAddModule ecId={`${this && this.props && this.props.ecId || ''}_ShareAddModule@s8g39a`}/>
            </div>
        )
    }
}


